package com.xinchao.job.task;

import com.google.common.collect.Lists;
import com.xinchao.job.service.NewsService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StopWatch;

import java.util.List;

/**
 * @ClassName GrabInfoJob
 * @Description 每天定时抓取新闻信息
 * @Author HanQinrui
 * @Date 2018/9/4 15:44
 * @Version 1.0
 **/
@DisallowConcurrentExecution
public class GrabNewsInfoJob extends QuartzJobBean {
    private static Logger logger = LoggerFactory.getLogger(GrabNewsInfoJob.class);

    @Autowired
    private NewsService newsService;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        logger.info("执行抓取新闻信息【GrabNewsInfoJob】" );
        List<String> newsList = Lists.newArrayList();
        try {
            // 抓取新闻
            //从一个URL加载一个Document对象。
            Document doc = Jsoup.connect("http://www.gov.cn/guowuyuan/index.htm").get();
            //选择“美食天下”所在节点
            Elements elements = doc.select("body > div.content.gwy > div > div.leftPart > div.chanel_tab_main.news > div.zl_channel_con > div > div");
            Elements elements1 = elements
                    .get(0)
                    .getElementsByTag("ul")
                    .get(0)
                    .select("a");
            for (int i = 0; i < elements1.size(); i++) {
                newsList.add(elements1.get(i).select("a").text());
            }
            // 保存新闻标题
            newsService.insertNews(newsList);
            stopWatch.stop();
            logger.info("【GrabNewsInfoJob】执行完毕，执行时间："+stopWatch.getTotalTimeSeconds());
        } catch (Exception e) {
            logger.info("【GrabNewsInfoJob】执行完毕，失败：" + e.toString());
        }
    }

}
